<template>
  <Draggable
    class="draggable-wrapper outer"
    ghostClass="ghost"
    :list="displayFormFields"
    item-key="index"
    :group="{ name: 'fields' }"
    :animation="200"
    handle=".selected"
  >
    <template #item="{ element: row }">
      <Draggable
        class="draggable-wrapper"
        :class="{ selected: currentFormKey === row.id }"
        tag="el-row"
        :component-data="{ props: { ...layoutConfig.row } }"
        :list="row"
        :group="{ name: 'fields' }"
        :animation="200"
        ghostClass="ghost"
        item-key="formKey"
      >
        <template #item="{ element: field }">
          <el-col
            v-bind="field.fieldProps?.col ?? layoutConfig.col"
            class="col-wrapper"
            :class="{ selected: currentFormKey === field.formKey }"
            @click.stop="handleSelectCol(field)"
          >
            <field-renderer
              :isPreview="true"
              :formLayout="layoutConfig.formLayout"
              :field="field"
              :formData="formData"
              v-model:value="formData[field.formKey]"
            />
          </el-col>
        </template>
      </Draggable>
    </template>
  </Draggable>
</template>

<script setup>
import { watch, ref, computed } from "vue";
import FieldRenderer from "./FieldRenderer.vue";
import Draggable from "vuedraggable";
import { useFormStore } from "@/store/form";

const props = defineProps({
  layoutConfig: { type: Object, default: () => ({}) },
  field: { type: Object, default: () => ({}) },
});

const emits = defineEmits(["click"]);

const store = useFormStore();

const formData = ref({});
const currentFormKey = ref("");

const displayFormFields = computed(() => {
  let result = [];
  let row = [];
  for (const field of props.field.fieldList) {
    if (!field.singleRow) {
      row.push(field);
      if (row.length === store.columnNum) {
        result.push(row);
        row = [];
      }
    } else {
      result.push(row);
      row = [];
      row.push(field);
      result.push(row);
      row = [];
    }
  }
  if (row.length > 0) {
    result.push(row);
  }
  result = result.filter((item) => item.length > 0);
  return result;
});

function handleSelectCol(record) {
  emits("selectField", record);
}
</script>

<style scoped lang="less">
.col-wrapper {
  padding-top: 5px;
  &:hover {
    background: #f6f7ff;
  }
  &.selected {
    background: #f6f7ff;
  }
}
.draggable-wrapper {
  width: 100%;
  &.outer {
    height: 100%;
  }
}
.drag-item {
  position: relative;
  &.selected {
    position: relative;
    border: 1px solid #409eff;
    .el-icon-drag {
      position: absolute;
      top: -5px;
      left: -5px;
      width: 20px;
      height: 20px;
      background: #409eff;
    }
    // &::before {
    //   content: "";
    //   position: absolute;
    //   top: -1px;
    //   left: -1px;
    //   width: 25px;
    //   height: 25px;
    //   background: #409eff;
    //   cursor: move;
    // }
  }
}
</style>
